import axios from 'axios';

axios.defaults.timeout = 5000;
// 配置默认 url
axios.defaults.baseURL = '/';
axios.defaults.withCredentials = true;

// http request 拦截器
axios.interceptors.request.use(
  (config) => {
    config.data = JSON.stringify(config.data);
    // config.paramsSerializer = (params) => {
    //   return JSON.stringify(params, { indices: false });
    // };
    // iView.LoadingBar.start();
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// http response 拦截器
axios.interceptors.response.use(
  (response) => {
    // iView.LoadingBar.finish();
    if (response.data.code === 404) {
      // router.push({
      //   path: '/login',
      //   querry: { redirect: router.currentRoute.fullPath },
      // });
    }
    if (response.data.code === 0) {
      return Promise.resolve(response.data.data);
    }
    return Promise.reject({
      error: '错误',
    });
  },
  (error) => {
    // iView.LoadingBar.error();
    return Promise.reject(error);
  }
);

/***
 * 封装 HTTP 请求
 * @param url
 * @param data
 * @return {Promise}
 */

function apiAxios(method: string, url: string, params?: any) {
  return new Promise((resolve, reject) => {
    axios({
      method: method,
      url: url,
      data: method === 'POST' || method === 'PUT' ? params : null,
      params: method === 'GET' || method === 'DELETE' ? params : null,
      headers:
        method === 'POST' || method === 'PUT'
          ? { 'Content-Type': 'application/json;charset=UTF-8' }
          : {
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            },
    })
      .then(function (res) {
        resolve(res);
      })
      .then(function (err) {
        reject(err);
      });
  });
}

export default {
  get: function (url: string) {
    return apiAxios('GET', url);
  },
  post: function (url: string, params: any) {
    return apiAxios('POST', url, params);
  },
  put: function (url: string, params: any) {
    return apiAxios('PUT', url, params);
  },
  delete: function (url: string, params: any) {
    return apiAxios('DELETE', url, params);
  },
};
